<template>
	<view class="battery-container">
		<view class="battery-body">
			<view class="battery" :style="{width: `${level}%`}"></view>
			<text class="iconfont icon-fl-dian charging" v-if="state===2"></text>
		</view>
		<view class="battery-head"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				state: 0,
				level: 0
			}
		},
		mounted() {
			this.getBatteryInfo()
		},
		methods: {
			// 获取电量
			getBatteryInfo() {
				if (uni.getSystemInfoSync().platform === 'ios') {
					let UIDevice = plus.ios.import("UIDevice")
					let dev = UIDevice.currentDevice()
					if (!dev.isBatteryMonitoringEnabled()) {
						dev.setBatteryMonitoringEnabled(true)
					}
					setInterval(() => {
						this.state = dev.batteryState()
						this.level = dev.batteryLevel() * 100
					}, 1000)
				} else {
					let main = plus.android.runtimeMainActivity()
					let Intent = plus.android.importClass('android.content.Intent')
					let recevier = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
						onReceive: (context, intent) => {
							let action = intent.getAction()
							if (action == Intent.ACTION_BATTERY_CHANGED) {
								this.state = intent.getIntExtra("status", 0) //电池状态  
								this.level = intent.getIntExtra("level", 0) //电量
							}
						}
					})
					let IntentFilter = plus.android.importClass('android.content.IntentFilter')
					let filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
					main.registerReceiver(recevier, filter)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.battery-container {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 25px;
		height: 10px;
		color: #808080;

		.battery-body {
			position: relative;
			padding: 1px;
			width: 22px;
			height: 100%;
			border-radius: 1px;
			border: 1px solid currentColor;

			.battery {
				height: 100%;
				background-color: currentColor;
			}

			.charging {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				height: 10px;
				line-height: 10px;
				font-size: 12px;
				color: #cacaca;
			}
		}

		.battery-head {
			width: 2px;
			height: 6px;
			background-color: currentColor;
		}
	}
</style>
